/**
 * 
 */
package com.infodms.dms.actions.sales.storageManage;

import java.io.OutputStream;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.infodms.dms.actions.partsmanage.purchase.PurchaseOrderSearch;
import com.infodms.dms.bean.AclUserBean;
import com.infodms.dms.common.Constant;
import com.infodms.dms.common.ErrorCodeConstant;
import com.infodms.dms.common.materialManager.MaterialGroupManagerDao;
import com.infodms.dms.dao.feedbackMng.StandardVipApplyManagerDao;
import com.infodms.dms.dao.partinfo.PartorderDao;
import com.infodms.dms.dao.sales.storageManage.ReturnVehicleReqDao;
import com.infodms.dms.dao.sales.storageManage.StorageQueryDAO;
import com.infodms.dms.exception.BizException;
import com.infodms.dms.po.TmVehiclePO;
import com.infodms.dms.po.TtIfStandardAuditPO;
import com.infodms.dms.po.TtIfStandardPO;
import com.infodms.dms.po.TtVsReturnVehicleReqPO;
import com.infodms.dms.util.CommonUtils;
import com.infodms.dms.util.csv.CsvWriterUtil;
import com.infodms.dms.util.sequenceUitl.SequenceManager;
import com.infoservice.mvc.context.ActionContext;
import com.infoservice.mvc.context.RequestWrapper;
import com.infoservice.mvc.context.ResponseWrapper;
import com.infoservice.po3.bean.PageResult;

/**
 * @Title: 退车Action
 * @Description:InfoFrame3.0.V01
 * @Copyright: Copyright (c) 2010
 * @Company: www.infoservice.com.cn
 * @Date: 2010-9-6
 * @author
 * @mail
 * @version 1.0
 * @remark
 */
public class ReturnVehicleReq {
	public Logger logger = Logger.getLogger(ReturnVehicleReq.class);
	private ActionContext act = ActionContext.getContext();
	private RequestWrapper request = act.getRequest();
	private final String url = "/jsp/sales/storageManage/returnVehicleReq.jsp";
	private final String queryUrl = "/jsp/sales/storageManage/queryReturnVehicleReq.jsp";
	private final String applyUrl = "/jsp/sales/storageManage/applyReturnVehicleReq.jsp";

	/*
	 * 退车申请初始化
	 */
	public void returnVehicleReqInit() {
		ActionContext act = ActionContext.getContext();
		AclUserBean logonUser = (AclUserBean) act.getSession().get(Constant.LOGON_USER);
		try {
			act.setForword(url);
		} catch (Exception e) {// 异常方法
			BizException e1 = new BizException(act, e,ErrorCodeConstant.QUERY_FAILURE_CODE, "退车申请初始化");
			logger.error(logonUser, e1);
			act.setException(e1);
		}
	}

	/*
	 * 退车申请
	 */
	public void returnVehicleReqQuery() {
		ActionContext act = ActionContext.getContext();
		AclUserBean logonUser = (AclUserBean) act.getSession().get(Constant.LOGON_USER);
		try {
			RequestWrapper request = act.getRequest();
			logonUser = (AclUserBean) act.getSession().get(Constant.LOGON_USER);	
			String materialCode =  CommonUtils.checkNull(request.getParamValue("materialCode"));
			String materialCode__ =  CommonUtils.checkNull(request.getParamValue("materialCode__"));	//物料
			String vin =  CommonUtils.checkNull(request.getParamValue("vin"));
			Long poseId = logonUser.getPoseId();
			Long comId = logonUser.getCompanyId() ;
			List<Map<String, Object>> areaList = MaterialGroupManagerDao
					.getDealerId(comId.toString(),poseId.toString());
			String dealerIds__ = "";
			for(int i=0; i<areaList.size();i++) {
				dealerIds__ += areaList.get(i).get("DEALER_ID").toString()+"," ;
			}
			dealerIds__ = dealerIds__.substring(0,(dealerIds__.length()-1)) ;				//当前用户职位对应的经销商ID
			ReturnVehicleReqDao dao = new ReturnVehicleReqDao();
			Integer curPage = request.getParamValue("curPage") != null ? Integer
					.parseInt(request.getParamValue("curPage"))
					: 1; // 处理当前页
			PageResult<Map<String, Object>> ps = dao.getReturnVehicleReq(dealerIds__,materialCode,materialCode__,vin,Constant.PAGE_SIZE, curPage);
			act.setOutData("ps", ps);
		} catch (Exception e) {
			BizException e1 = new BizException(act, e,ErrorCodeConstant.QUERY_FAILURE_CODE, "退车申请");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	
	/*
	 * 提交退车申请
	 */
	public void returnVehicleReqdo(){
		ActionContext act = ActionContext.getContext();
		AclUserBean logonUser = (AclUserBean) act.getSession().get(Constant.LOGON_USER);
		try {
			String[] vehicleIds = request.getParamValues("vehicleIds");     //申请单号  数组类型
			String reason = CommonUtils.checkNull(request.getParamValue("reason"));//退车原因
			
			
			ReturnVehicleReqDao dao = new ReturnVehicleReqDao();
			//循环遍历插入TT_VS_RETURN_VEHICLE_REQ
			
			if(vehicleIds!=null || !vehicleIds.equals("")){
				for(int i=0;i<vehicleIds.length;i++){
					String vehicleId = vehicleIds[i];
					String a = vehicleId.substring(0, vehicleId.indexOf("||")); 
					String b = vehicleId.substring(vehicleId.indexOf("||")+2);
					TtVsReturnVehicleReqPO po = new TtVsReturnVehicleReqPO();
					Long reqId = Long.parseLong(SequenceManager.getSequence("")) ;
					String reqNo = "TC" + reqId ;
					po.setReqId(reqId);//ID
					po.setReqNo(reqNo) ; //No
					po.setVehicleId(Long.parseLong(a));//车辆表ID
					po.setDealerId(Long.parseLong(b));//经销商ID
					po.setAreaid(dao.getVAreaId(a));
					po.setReason(reason);//退车原因
					po.setStatus(Integer.parseInt(Constant.RETURN_STATUS_01));
					po.setRaiseDate(new Date());
					po.setCompanyId(Long.parseLong(logonUser.getOemCompanyId()));
					po.setCreateBy(logonUser.getUserId());
					po.setCreateDate(po.getRaiseDate());
					dao.insert(po);
					TmVehiclePO aa = new TmVehiclePO();
					TmVehiclePO bb = new TmVehiclePO();
					aa.setVehicleId(Long.parseLong(a));
					bb.setLockStatus(Constant.LOCK_STATUS_05);
					bb.setUpdateBy(po.getCreateBy());
					bb.setUpdateDate(po.getRaiseDate());
					dao.update(aa, bb);//给车辆加退车锁
				}
			}
			act.setOutData("returnValue", 1);  //前台回调函数的参数
		} catch (Exception e) {
			BizException e1 = new BizException(act, e,ErrorCodeConstant.PUTIN_FAILURE_CODE, "退车申请");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	
	/*
	 * 退车查询
	 */
	public void returnVehicleQueryInit(){
		ActionContext act = ActionContext.getContext();
		AclUserBean logonUser = (AclUserBean) act.getSession().get(Constant.LOGON_USER);
		try {
			act.setForword(queryUrl);
		} catch (Exception e) {// 异常方法
			BizException e1 = new BizException(act, e,ErrorCodeConstant.QUERY_FAILURE_CODE, "退车查询初始化");
			logger.error(logonUser, e1);
			act.setException(e1);
		}
	}
	
	/*
	 * 退车查询
	 */
	public void returnVehicleQuery(){
		ActionContext act = ActionContext.getContext();
		AclUserBean logonUser = (AclUserBean) act.getSession().get(Constant.LOGON_USER);
		try {
			RequestWrapper request = act.getRequest();
			logonUser = (AclUserBean) act.getSession().get(Constant.LOGON_USER);	
			String materialCode =  CommonUtils.checkNull(request.getParamValue("materialCode"));
			String materialCode__ =  CommonUtils.checkNull(request.getParamValue("materialCode__"));	//物料
			String vin =  CommonUtils.checkNull(request.getParamValue("vin"));
			String status = CommonUtils.checkNull(request.getParamValue("status"));
			ReturnVehicleReqDao dao = new ReturnVehicleReqDao();
			Long poseId = logonUser.getPoseId();
			Long comId = logonUser.getCompanyId() ;
			List<Map<String, Object>> areaList = MaterialGroupManagerDao.getDealerId(comId.toString(),poseId.toString());
			
			String orgId = "" ;
			String dutyType = logonUser.getDutyType() ;
			
			if(Constant.DUTY_TYPE_LARGEREGION.toString().equals(dutyType)) {
				orgId = logonUser.getOrgId().toString() ;
			}
			
			String dealerIds__ = "";
			
			for(int i=0; i<areaList.size();i++) {
				dealerIds__ += areaList.get(i).get("DEALER_ID").toString()+"," ;
			}
			
			if(dealerIds__ != null && !"".equals(dealerIds__)){
				dealerIds__ = dealerIds__.substring(0,(dealerIds__.length()-1)) ;				//当前用户职位对应的经销商ID
			}
			
			String areaIds = MaterialGroupManagerDao.getAreaIdsByPoseId(logonUser.getPoseId());
			
			Integer curPage = request.getParamValue("curPage") != null ? Integer.parseInt(request.getParamValue("curPage")) : 1; // 处理当前页
			PageResult<Map<String, Object>> ps = dao.getQueryReturnVehicleReq(orgId, status,dealerIds__,materialCode,materialCode__,vin,areaIds,Constant.PAGE_SIZE, curPage);
			
			act.setOutData("ps", ps);
		} catch (Exception e) {
			BizException e1 = new BizException(act, e,ErrorCodeConstant.QUERY_FAILURE_CODE, "退车");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	
	/*
	 * 车厂端查询退车申请
	 */
	public void returnVehicleQueryOEMInit(){
		returnVehicleQueryInit();
	}
	
	/*
	 * 退车申请审核
	 */
	public void returnVehicleApplyInit(){
		ActionContext act = ActionContext.getContext();
		AclUserBean logonUser = (AclUserBean) act.getSession().get(Constant.LOGON_USER);
		try {
			Long poseId = logonUser.getPoseId();
			List<Map<String, Object>> areaList = MaterialGroupManagerDao.getPoseIdBusiness(poseId.toString());
			areaList.size();
			act.setOutData("areaList", areaList);
			act.setForword(applyUrl);
		} catch (Exception e) {// 异常方法
			BizException e1 = new BizException(act, e,ErrorCodeConstant.QUERY_FAILURE_CODE, "退车申请审核");
			logger.error(logonUser, e1);
			act.setException(e1);
		}
	}
	
	/*
	 *退车申请列表 
	 */
	public void applyReturnVehicleQuery(){
		ActionContext act = ActionContext.getContext();
		AclUserBean logonUser = (AclUserBean) act.getSession().get(Constant.LOGON_USER);
		try {
			RequestWrapper request = act.getRequest();
			logonUser = (AclUserBean) act.getSession().get(Constant.LOGON_USER);	
			String materialCode =  CommonUtils.checkNull(request.getParamValue("materialCode"));
			String materialCode__ =  CommonUtils.checkNull(request.getParamValue("materialCode__"));	//物料
			String vin =  CommonUtils.checkNull(request.getParamValue("vin"));
			String areaId = CommonUtils.checkNull(request.getParamValue("areaId"));
			String dealerId = CommonUtils.checkNull(request.getParamValue("dealerId"));
			ReturnVehicleReqDao dao = new ReturnVehicleReqDao();
			
			String orgId = "" ;
			String dutyType = logonUser.getDutyType() ;
			
			if(Constant.DUTY_TYPE_LARGEREGION.toString().equals(dutyType)) {
				orgId = logonUser.getOrgId().toString() ;
			}
			
			Integer curPage = request.getParamValue("curPage") != null ? Integer.parseInt(request.getParamValue("curPage")) : 1; // 处理当前页
			
			PageResult<Map<String, Object>> ps = dao.getApplyReturnVehicleReq(orgId, dealerId, areaId,materialCode,materialCode__,vin,Constant.PAGE_SIZE, curPage);
			
			act.setOutData("ps", ps);
		} catch (Exception e) {
			BizException e1 = new BizException(act, e,ErrorCodeConstant.QUERY_FAILURE_CODE, "退车");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	
	/*
	 * 退车审核操作
	 * flag = 1 通过
	 * flag = 2 驳回
	 */
	public void returnVehicleReqApplydo(){
		ActionContext act = ActionContext.getContext();
		AclUserBean logonUser = (AclUserBean) act.getSession().get(Constant.LOGON_USER);
		try {
			String[] vehicleIds = request.getParamValues("vehicleIds");     //申请单号  数组类型
			String reason = CommonUtils.checkNull(request.getParamValue("reason"));//退车原因
			String flag = request.getParamValue("flag");
			
			ReturnVehicleReqDao dao = new ReturnVehicleReqDao();
			//循环遍历插入TT_VS_RETURN_VEHICLE_REQ
			
			if(vehicleIds!=null || !vehicleIds.equals("")){
				for(int i=0;i<vehicleIds.length;i++){
					TtVsReturnVehicleReqPO po = new TtVsReturnVehicleReqPO();
					TtVsReturnVehicleReqPO tp = new TtVsReturnVehicleReqPO();
					String[] vehicleReq = vehicleIds[i].split("-");
					po.setReqId(Long.parseLong(vehicleReq[1])) ;
					tp.setUpdateBy(logonUser.getUserId());
					tp.setUpdateDate(new Date());
					tp.setCheckDate(tp.getUpdateDate());
					tp.setCheckRemark(reason);
					if(flag.equals("1")){
						tp.setStatus(Integer.parseInt(Constant.RETURN_STATUS_02));
					}else{
						tp.setStatus(Integer.parseInt(Constant.RETURN_STATUS_03));
					}
					dao.update(po, tp);//修改退车申请表
					
					
					StringBuffer sql = new StringBuffer();
					sql.append("UPDATE tm_vehicle\n");
					sql.append("   SET update_by   ="+tp.getUpdateBy()+",\n");
					sql.append("       update_date = sysdate\n"); 
					if(flag.equals("1")){
						sql.append("       ,dealer_id   = NULL,\n" ); 
						sql.append("       life_cycle  = "+Constant.VEHICLE_LIFE_02+"\n" ); 
					}
					sql.append("       ,lock_status = "+ Constant.LOCK_STATUS_01 +"\n" ); 

					sql.append(" WHERE vehicle_id ="+Long.parseLong(vehicleReq[0]));										
					dao.update(sql.toString(),null);//解锁并更改车辆生命周期
					if(flag.equals("1")){
			  			// 调用发运存储过程
						List<Object> ins = new LinkedList<Object>();
						ins.add(vehicleReq[1]);

						List<Integer> outs = new LinkedList<Integer>();
						
						dao.callProcedure("p_return_vehicle_req_to_erp", ins, outs);	
					}
				}
			}
			act.setOutData("returnValue", 1);  //前台回调函数的参数
		} catch (Exception e) {
			BizException e1 = new BizException(act, e,ErrorCodeConstant.PUTIN_FAILURE_CODE, "退车申请");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}

	/**
	 * 车辆退回基地下载
	 *  add by yx 20110228
	 */
	public void returnVehicleToBaseDownLoad(){
		AclUserBean logonUser = null;
		RequestWrapper request = act.getRequest();
		ResponseWrapper response = act.getResponse();
		logonUser = (AclUserBean) act.getSession().get(Constant.LOGON_USER);
//		act.getSession().get(Constant.LOGON_USER);

		// 导出的文件名
		String fileName = "车辆退回基地下载.csv";
		// 导出的文字编码
		OutputStream os = null;
		try {
			String materialCode =  CommonUtils.checkNull(request.getParamValue("materialCode"));
			String materialCode__ =  CommonUtils.checkNull(request.getParamValue("materialCode__"));	//物料
			String vin =  CommonUtils.checkNull(request.getParamValue("vin"));
			Long poseId = logonUser.getPoseId();
			Long comId = logonUser.getCompanyId() ;
			List<Map<String, Object>> areaList = MaterialGroupManagerDao
					.getDealerId(comId.toString(),poseId.toString());
			String dealerIds__ = "";
			for(int i=0; i<areaList.size();i++) {
				dealerIds__ += areaList.get(i).get("DEALER_ID").toString()+"," ;
			}
			dealerIds__ = dealerIds__.substring(0,(dealerIds__.length()-1)) ;				//当前用户职位对应的经销商ID
			ReturnVehicleReqDao dao = new ReturnVehicleReqDao();
			Integer curPage = request.getParamValue("curPage") != null ? Integer
					.parseInt(request.getParamValue("curPage"))
					: 1; // 处理当前页

			fileName = new String(fileName.getBytes("GB2312"), "ISO8859-1");
			response.setContentType("Application/text/csv");
			response.addHeader("Content-Disposition", "attachment;filename="+ fileName);

			List<List<Object>> list = new LinkedList<List<Object>>();
			List<Object> listTemp = new LinkedList<Object>();
			listTemp.add("车型名称");
			listTemp.add("配置");
			listTemp.add("物料代码");
			listTemp.add("物料名称");
			listTemp.add("VIN");
			listTemp.add("位置说明");
			listTemp.add("经销商");
			listTemp.add("库存状态");
			listTemp.add("入库日期");
			list.add(listTemp);
			PageResult<Map<String, Object>> ps = dao.getReturnVehicleReq(dealerIds__,materialCode,materialCode__,vin,100000, curPage);
			List<Map<String, Object>> results = ps.getRecords();
			if(results!=null && !results.equals("")){
			for (int i = 0; i < results.size(); i++) {
				Map<String, Object> record = results.get(i);
				listTemp = new LinkedList<Object>();
				listTemp.add(CommonUtils.checkNull(record.get("MODEL_NAME")));
				listTemp.add(CommonUtils.checkNull(record.get("PACKAGE_NAME")));
				listTemp.add(CommonUtils.checkNull(record.get("MATERIAL_CODE")));
				listTemp.add(CommonUtils.checkNull(record.get("MATERIAL_NAME")));
				listTemp.add(CommonUtils.checkNull(record.get("VIN")));
				listTemp.add(CommonUtils.checkNull(record.get("WAREHOUSE_NAME")));
				listTemp.add(CommonUtils.checkNull(record.get("DEALER_SHORTNAME")));
				listTemp.add(CommonUtils.checkNull(record.get("LIFE_CYCLE_DESC")));
				listTemp.add(CommonUtils.checkNull(record.get("STORAGE_TIME")));
				list.add(listTemp);
			}
			}
			os = response.getOutputStream();
			CsvWriterUtil.writeCsv(list, os);		
			os.flush();
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE,"车辆退回基地下载");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
	
	/**
	 * 车辆退车下载
	 *  add by yx 20110228
	 */
	public void vhclBackDownLoad(){
		AclUserBean logonUser = null;
		RequestWrapper request = act.getRequest();
		ResponseWrapper response = act.getResponse();
		logonUser = (AclUserBean) act.getSession().get(Constant.LOGON_USER);
//		act.getSession().get(Constant.LOGON_USER);

		// 导出的文件名
		String fileName = "车辆退车下载.csv";
		// 导出的文字编码
		OutputStream os = null;
		try {
			String materialCode =  CommonUtils.checkNull(request.getParamValue("materialCode"));
			String materialCode__ =  CommonUtils.checkNull(request.getParamValue("materialCode__"));	//物料
			String vin =  CommonUtils.checkNull(request.getParamValue("vin"));
			String status = CommonUtils.checkNull(request.getParamValue("status"));
			ReturnVehicleReqDao dao = new ReturnVehicleReqDao();
			Long poseId = logonUser.getPoseId();
			Long comId = logonUser.getCompanyId() ;
			
			String orgId = "" ;
			String dutyType = logonUser.getDutyType() ;
			
			if(Constant.DUTY_TYPE_LARGEREGION.toString().equals(dutyType)) {
				orgId = logonUser.getOrgId().toString() ;
			}
			
			List<Map<String, Object>> areaList = MaterialGroupManagerDao
					.getDealerId(comId.toString(),poseId.toString());
			String dealerIds__ = "";
			for(int i=0; i<areaList.size();i++) {
				dealerIds__ += areaList.get(i).get("DEALER_ID").toString()+"," ;
			}
			if(dealerIds__ != null && !"".equals(dealerIds__)){
				dealerIds__ = dealerIds__.substring(0,(dealerIds__.length()-1)) ;				//当前用户职位对应的经销商ID
			}
			String areaIds = MaterialGroupManagerDao.getAreaIdsByPoseId(logonUser.getPoseId());
			Integer curPage = request.getParamValue("curPage") != null ? Integer
					.parseInt(request.getParamValue("curPage"))
					: 1; // 处理当前页
			fileName = new String(fileName.getBytes("GB2312"), "ISO8859-1");
			response.setContentType("Application/text/csv");
			response.addHeader("Content-Disposition", "attachment;filename="+ fileName);

			List<List<Object>> list = new LinkedList<List<Object>>();
			List<Object> listTemp = new LinkedList<Object>();
			listTemp.add("退车号");
			listTemp.add("车型名称");
			listTemp.add("配置");
			listTemp.add("物料代码");
			listTemp.add("物料名称");
			listTemp.add("VIN");
			listTemp.add("经销商");
			listTemp.add("申请时间");
			listTemp.add("申请原因");
			listTemp.add("审核时间");
			listTemp.add("审核结果");
			listTemp.add("审核状态");
			list.add(listTemp);
			//List<Map<String, Object>> results  = dao.getLoadDealerVhclDetail(areaIds.toString(),dealerIds, vin, companyId, 99999999, Constant.PAGE_SIZE);
			PageResult<Map<String, Object>> ps = dao.getQueryReturnVehicleReq(orgId, status,dealerIds__,materialCode,materialCode__,vin,areaIds,100000, curPage);
			List<Map<String, Object>> results = ps.getRecords();
			if(results!=null && !results.equals("")){
			for (int i = 0; i < results.size(); i++) {
				Map<String, Object> record = results.get(i);
				listTemp = new LinkedList<Object>();
				listTemp.add(CommonUtils.checkNull(record.get("REQ_NO")));
				listTemp.add(CommonUtils.checkNull(record.get("MODEL_NAME")));
				listTemp.add(CommonUtils.checkNull(record.get("PACKAGE_NAME")));
				listTemp.add(CommonUtils.checkNull(record.get("MATERIAL_CODE")));
				listTemp.add(CommonUtils.checkNull(record.get("MATERIAL_NAME")));
				listTemp.add(CommonUtils.checkNull(record.get("VIN")));
				listTemp.add(CommonUtils.checkNull(record.get("DEALER_NAME")));
				listTemp.add(CommonUtils.checkNull(record.get("RAISE_DATE")));
				listTemp.add(CommonUtils.checkNull(record.get("REASON")));
				listTemp.add(CommonUtils.checkNull(record.get("CHECK_DATE")));
				listTemp.add(CommonUtils.checkNull(record.get("CHECK_REMARK")));
				listTemp.add(CommonUtils.checkNull(record.get("REQ_STATUS_DESC")));
				list.add(listTemp);
			}
			}
			os = response.getOutputStream();
			CsvWriterUtil.writeCsv(list, os);		
			os.flush();
		}catch(Exception e) {//异常方法
			BizException e1 = new BizException(act,e,ErrorCodeConstant.QUERY_FAILURE_CODE,"车辆退车下载");
			logger.error(logonUser,e1);
			act.setException(e1);
		}
	}
}
